<template>
  <div class="coordinate-form">
    <Dialog :title="dialogTitle" v-model="dialogVisible">
      <SmForm
        class="-mb-15px"
        ref="formRef"
        isCol
        label-width="150px"
        v-model="formData"
        v-loading="formLoading"
        :options="requestFormOptions"
        :getModelValue="getFormData"
      >
        <template #idCard>
          <MultiImageUpload
            v-model="formData.imgList"
            :limit="1"
            @update:model-value="(val) => changeOneImg(val, formData, 'idCard')"
          />
        </template>
        <template #businessLicense>
          <MultiImageUpload
            v-model="formData.imgList1"
            :limit="1"
            @update:model-value="(val) => changeOneImg(val, formData, 'businessLicense')"
          />
        </template>
      </SmForm>

      <template #footer>
        <el-button @click="submitFormDB" type="primary" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </template>
    </Dialog>
  </div>
</template>
<script setup lang="ts">
import { createUser, getRoleList, getUser, updateUser } from "@/api/user";
import { addProperty } from "@/components/SmForm/src/utils";
import { createDBFn } from "@/utils/decorate";
import { defaultProps } from "@/utils/tree";
// import { mockTreeList } from "./data";
import {
  getCoordinateTypeList,
  getDeptList,
  getDeptTree,
  getOrganizationList,
  getProvinceCityDistrictList,
  getUserList,
} from "@/commonData";
// import { useAuth } from "../hooks/useAuth";
import DeptAPI from "@/api/system/dept-api";
import { changeOneImg } from "@/utils/changeData";
import { phoneRules } from "@/commonData/rules";
import { useTableData } from "@/components/SmTable/src/utils";
import { enableList, isNotList, salespersonTypeList } from "@/commonData/dict";

/** 仓库 表单 */
defineOptions({ name: "EmployeeOnboard" });

const { t } = useI18n(); // 国际化

const dialogVisible = ref(false); // 弹窗的是否展示
const dialogTitle = ref("统筹信息"); // 弹窗的标题
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(""); // 表单的类型：create - 新增；update - 修改
const initDefaultData = () => {
  return {
    guaranteeNum: 365,
  };
};
const initFormData = () => {
  const defaultData = initDefaultData();
  const data = {};
  Object.assign(data, defaultData);
  return data;
};
const formData: any = ref(initFormData());
const formRef = ref(); // 表单 Ref
const deptTree = ref([]);
const organizationList = ref([]);
const coordinateTypeList = ref([]);
const userList = ref([]);
const { provinceList, cityList, districtList } = getProvinceCityDistrictList(formData, formRef);
const deptList = ref([]);

// const {
//   isExpanded,
//   permKeywords,
//   checkedRole,
//   permTreeRef,
//   getMenuTreeAndRoleMenu,
//   menuTree,

//   setRoleMenu,
//   handlePermFilter,
//   togglePermTree,
//   handleAssignPermSubmit,
// } = useAuth();

// 只有选中时才有-调用接口拿到的时候也需要加
const check = (checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys) => {
  formData.value.menuIds = checkedKeys?.checkedKeys;
  console.log(
    checkedNodes,
    checkedKeys,
    halfCheckedNodes,
    halfCheckedKeys,
    "checkedNodes,checkedKeys,halfCheckedNodes,halfCheckedKeys"
  );
};

/** 打开弹窗 */
const open = async (type: string, id?: string) => {
  dialogVisible.value = true;
  // dialogTitle.value = t("action." + type);
  formType.value = type;
  resetForm();

  getOrganizationList(organizationList);

  getDeptTree(deptTree);
  getCoordinateTypeList(coordinateTypeList);
  getUserList(userList);
  getDeptList(deptList);

  // if (!id) {
  //   getMenuTreeAndRoleMenu();
  // }

  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    try {
      const data = await DeptAPI.getFormData(id);
      const defaultData = initDefaultData();
      Object.assign(data, defaultData);
      formRef.value = data;

      // getMenuTreeAndRoleMenu(formData.value);
      // 主动触发表单数据回显
      formRef.value.initForm();
    } finally {
      formLoading.value = false;
    }
  }
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(["success"]); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as any;
    if (formType.value === "create") {
      await createUser(data);
      // ElMessage.success("操作成功");
    } else if (formType.value === "update") {
      await updateUser(data);
      // ElMessage.success("操作成功");
    }
    ElMessage.success("操作成功");
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit("success");
  } finally {
    formLoading.value = false;
  }
};
const submitFormDB = createDBFn(submitForm);

/** 重置表单 */
const resetForm = () => {
  formData.value = initFormData();
  formRef.value?.resetFields();
};

const requestFormOptions: any = ref([]);
const createRequestFormOptions = () => {
  /**
    1、创建销售员资料心下
    第一步创建账户信息-第二部创建行政信息-第三步创建执证资料库-完成资料信息创建成功
    实际体验两步就完成了 (完成完全可用tooltips提醒成功即可)

    1、创建销售员资料信息


    1、用户类型-必填-下拉(直属-外聘)
    2、中文姓名-必填
    3、英文姓名
    4、手机号-必填
    5、邮箱
    6、证件类型-必填
    7、证件号
    8、性别-下拉(男女)
    9、出生日期
    10、婚姻状态-(未婚-已婚-离婚)
    11、民族-(56个民族)
    12、政治面貌-下拉-(百度搜素)
    13、健康状态-下拉(健康-一般)
    14、血型-下拉
    15-籍贯
    16-户口所在地
    17、常住地址(省市区联动)
    18、常住详细地址
    19、常住地址邮编
    20-住宅电话
    21-毕业院校
    22-毕业时间
    23-学历
    24-专业
    25-开户行
    26-银行账号
    27-初次参加工作时间
    28-原工作单位
    29-原工作职务
 */

  /**
    2、创建行政信息
    1、所属机构-下拉-必填
    2、所属团队-下拉-必填-(改成部门)
    3、销售人员类型-下拉-必填
    4、工号-必填
    5、任职岗级-下拉
    6、入司时间
    7、是否二次入司-下拉
    8、合同编号
    9、推荐人工号-禁用(一旦确定，无法更改)
    10、推荐人姓名-下拉

    (按钮 下一步-返回上一步)
   */

  /**
    1、销售信息暂时不动-因为有销售人员字段
    2、行政信息可以写
    */

  const administrationList = [
    {
      requiredFlag: true,
      type: "tree-select",
      placeholder: "归属机构",
      prop: "orgId",
      label: "归属机构",
      attrs: {
        filterable: true,
        clearable: true,
        // data: mockTreeList,
        data: organizationList,
        // props: defaultProps,
        "check-strictly": true,
        // "node-key": "id",
      },
    },
    {
      requiredFlag: true,
      type: "select",
      placeholder: "归属部门",
      label: "归属部门",
      prop: "deptId",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: deptList,
    },
    {
      requiredFlag: true,
      type: "select",
      placeholder: "销售人员类型",
      label: "销售人员类型",
      prop: "salespersonType",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: salespersonTypeList,
    },
    {
      requiredFlag: true,
      type: "input",
      label: "工号",
      prop: "workCode",
      placeholder: "工号",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      type: "select",
      placeholder: "任职岗级",
      label: "任职岗级",
      prop: "level",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: salespersonTypeList,
    },
    {
      type: "select",
      placeholder: "是否二次入司",
      label: "是否二次入司",
      prop: "isCompany",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: isNotList,
    },
    {
      type: "input",
      label: "合同编号",
      prop: "contractNo",
      placeholder: "合同编号",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      type: "select",
      placeholder: "推荐人工号",
      label: "推荐人工号",
      prop: "salespersonType",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: userList,
    },
    {
      type: "input",
      label: "推荐人姓名",
      prop: "referrerName",
      placeholder: "推荐人姓名",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
  ];

  const list = [...administrationList];

  addProperty(list);
  return list;
};
requestFormOptions.value = createRequestFormOptions();

const getFormData = () => {
  return formData.value;
};
</script>
